package com.example.taluo.service;

import com.example.taluo.entity.User;

import com.example.taluo.mapper.UserMapper;
import com.mysql.cj.log.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static java.rmi.server.LogStream.log;

/*** @Author supersaiya
 * @Description TODO

 * @Date 2025/2/15 18:39

 * @Version 1.0*/
@Service
@Slf4j
public class UserService {


    private final PasswordEncoder passwordEncoder;

    private final UserMapper userMapper;

    public UserService(PasswordEncoder passwordEncoder, UserMapper userMapper) {
        this.passwordEncoder = passwordEncoder;
        this.userMapper = userMapper;
    }
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }
    public User authenticate(String username, String password) {
        User user = userMapper.getUserByUsername(username);
        System.out.println("user = " + user.getUsername());
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }
    public User getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    public User addUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setEloRating(1000);//设置elo值
        //设置日期
        user.setAddTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setLastLogin(LocalDateTime.now());
        //设置用户状态
        user.setStatus((byte) 1);
        user.setDraws(0);
        user.setLosses(0);
        user.setWins(0);
        //插入数据库
        userMapper.addUser(user);
        return user;
    }

    public User updateUser(User user) {
        userMapper.updateUser(user);
        return user;
    }

    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }
}
